# -*- coding: utf-8 -*-
"""
Module Description:
Date: 2017/12/1
Author:Bai Jin Ping
"""
import zope.component
from pyshare.bll import events
from pyshare.const.enums.role import RoleBehaviorEventType
from datetime import datetime, timedelta
from app.area.core.component_center import ComponentCenter
from pyshare.const.enums.task import ActCdtSecondType, BehaviourInvolve
from pyshare.utils.time_utils import getCT
from pyshare.framework.dal.dal_manager import TransactionDelegator
from pyshare.core.context import action_context_storage
from pyshare.const.lang_enum import LangEnum


class RoleMixin(object):
    def update_login_record(self, is_create=False):
        """
        用于处理登录天数的方法
        :param is_create: 是否是新建角色
        :return: 是否当天的首次登录
        """
        cur_time = getCT()
        today_first_login = 1

        if is_create:
            # 创建角色,因为LastLoginTime是当天,避免与一天中非首次登录不作处理的逻辑冲突,故单独处理,默认连续登录1天
            self.sequent_login_day = 1

        else:
            # 非创建登录，根据LastLoginTime判断是否连续登录，当天多次登录的情况只对首次登录作处理，即LastLoginTime在当天时不处理
            yesterday = cur_time - timedelta(days=1)
            if ((not self.last_login_time)
                    or self.last_login_time < datetime(yesterday.year,
                                                       yesterday.month,
                                                       yesterday.day,
                                                       0,
                                                       0,
                                                       0)):
                # 昨天没有登录
                self.sequent_login_day = 1
            elif self.last_login_time < datetime(cur_time.year, cur_time.month, cur_time.day, 0, 0, 0):
                # 昨天登录过
                self.sequent_login_day += 1

        self_last_login_time = self.last_login_time

        if not is_create and self_last_login_time.date() == cur_time.date():
            # 不是今日登录
            today_first_login = 0

        self.last_login_time = cur_time

        from pyshare.dal.repository_impl import RoleRepository

        with TransactionDelegator():
            RoleRepository.save(self)

            if today_first_login:
                ComponentCenter().behaviour.handle_behaviour_execute_sync(
                    self.role_guid,
                    ActCdtSecondType.TotalLoginDay,
                    involve_type=BehaviourInvolve.Achievement)
                # 玩家行为事件
                role_event = events.RoleBehaviorProgressChanged(
                    role_id=self.role_guid, behavior_type=RoleBehaviorEventType.TotalLoginDay, add_value=1
                )
                zope.component.handle(role_event)

        return today_first_login

    def get_user_language_code(self):
        """
        获取用户语言
        """
        # 默认zh-cn
        if not self.language_code:
            return LangEnum.Simplified

        return self.language_code

    def update_user_language_code(self, code=None):
        """
        更新用户语言
        """
        if code is None:
            code = str(action_context_storage.ctx.lang)

        self.language_code = code

        # version :3.41
        # 优化登录减少TbRole save次数 删除原先的save操作

    def update_role_cache(self, field, val):
        """
        刷新角色缓存信息
        :param field: RoleInfo.default_var内所拥有字段
        :param val: 修改的信息
        :return:
        """
        rid, server_id = '', 0
        try:
            rid, server_id = self.role_guid, self.srv_id
            from pyshare.bll.utils.share.share_role_information import ShareRoleInformation
            role_cache = ShareRoleInformation.get_role_information_from_cache_db(self.role_guid, self.srv_id)
            if role_cache:
                role_dict = role_cache._asdict()
                role_dict[field] = val
                ShareRoleInformation.set_role_information(self.role_guid, role_dict)
        except Exception as e:
            try:
                from pyshare.framework import runtime_logger as log
                from pyshare.utils.traceback_utils import print_exc
                log.warning('UpdateRoleCacheError: rid: {}, server_id: {}, field: {} \n {}'.
                            format(rid, server_id, field, print_exc(e)))
            except Exception as e:
                pass
